package com.googlecode.openbox.common;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

public class ToolUtils {

	public static InputStream getInputStreamByProjectRelativePath(
			String projectRelativePath) {
		return ToolUtils.class.getClassLoader().getResourceAsStream(
				projectRelativePath);
	}

	public static String getStringFromStream(InputStream is) {
		if (null == is) {
			throw new RuntimeException(
					"Convert Stream to String failed as input stream is null");
		}
		BufferedReader br = new BufferedReader(new InputStreamReader(is));
		StringBuilder sb = new StringBuilder();
		char[] buffer = new char[2048];
		try {
			int len = -1;
			while (-1 != (len = br.read(buffer))) {
				sb.append(buffer, 0, len);
			}
		} catch (IOException e) {
			throw new RuntimeException("Convert Stream to String failed !", e);
		}
		String content = sb.toString();
		return content;
	}

	public static void closeInputStream(InputStream instream) {
		if (instream != null) {
			try {
				instream.close();
			} catch (IOException e) {
				System.err.println("close input stream failed!!!");
			}
		}
	}

	public static String getContent(String projectRelativePath) {
		InputStream contentStream = null;
		try {
			return getStringFromStream(getInputStreamByProjectRelativePath(projectRelativePath));
		} catch (Exception e) {
			throw new RuntimeException(e);
		} finally {
			closeInputStream(contentStream);
		}
	}

	public static void printUsage() {
		System.out.println(ToolUtils.getContent("readme"));
	}

}
